package com.makingTeam.config.disruptor;

import cn.hutool.core.thread.ThreadFactoryBuilder;
import com.lmax.disruptor.BlockingWaitStrategy;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;
import com.makingTeam.comment.thread.ThreadPoolFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
/**
 *
 * user: pzy
 * date: 2025/4/28 17:59
 */
@Configuration
@Slf4j
public class DisMQManager {



    @Bean
    @Primary
    public RingBuffer<MessageModel> ringBuffer(){
        ExecutorService executor = Executors.newFixedThreadPool(2,createThreadFactory("disruptor"));
        //环形队列大小，2的指数
        int bufferSize = 1024 * 256;
        //创建disruptor,单线程生产者
        Disruptor<MessageModel> disruptor = new Disruptor<>(new DisEventFactory(),
                bufferSize, executor, ProducerType.SINGLE,new BlockingWaitStrategy());
        //绑定消费者处理器
        disruptor.handleEventsWith(new DisEventHandler());
        //启动disruptor
        disruptor.start();
        ThreadFactory threadFactory = ThreadFactoryBuilder.create()
                .setNamePrefix("thread-")
                .build();
        return disruptor.getRingBuffer();
    }


    public static ThreadFactory createThreadFactory(String namePrefix) {
        AtomicInteger counter = new AtomicInteger(0);
        return r -> {
            Thread thread = new Thread(r);
            thread.setName(namePrefix + "-" + counter.incrementAndGet());
            thread.setDaemon(false);
            thread.setPriority(Thread.NORM_PRIORITY);
            // 设置异常处理器
            thread.setUncaughtExceptionHandler((t, e) ->
                    log.error("Uncaught exception in thread {}: {}", t.getName(), e.getMessage()));
            return thread;
        };
    }

}
